﻿using System.Collections.Generic;
using System.Text.Json;
using Newtonsoft.Json.Linq;

namespace DynamicChart.Util;

public static class DataProcessor
{
    public static IEnumerable<(string TableKey, string ColumnKey, Dictionary<string, object> Entity)> EnumerateFields(
        IDictionary<string, object> data)
    {
        foreach (var tableKey in data.Keys)
        {
            var columnDictionary = GetDictionaryFromJsonElement(data[tableKey]);
            if (columnDictionary == null) continue;

            foreach (var columnKey in columnDictionary.Keys)
            {
                var entity = GetDictionaryFromJsonElement(columnDictionary[columnKey]);
                if (entity == null) continue;

                yield return (tableKey, columnKey, entity);
            }
        }
    }

    private static Dictionary<string, object> GetDictionaryFromJsonElement(object jsonElement)
    {
        // 将 JsonElement 序列化为 JSON 字符串
        string jsonString = JsonSerializer.Serialize(jsonElement);

        // 再反序列化为 Dictionary<string, object>
        return JsonSerializer.Deserialize<Dictionary<string, object>>(jsonString);
    }
}